package com.yc.baseapi;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

public class TestWeakReferenceQueue {
	
	private Integer _1M = 1000000;
	private ReferenceQueue referenceQueue = new ReferenceQueue<byte[]>();
	
	public void m1() {
		Object value = new Object();
		Map<Object, Object> map = new HashMap<>();
		for(int i = 0;i < 1000;i++) {
		    byte[] bytes = new byte[_1M];
		    WeakReference<byte[]> weakReference = new WeakReference<byte[]>(bytes, referenceQueue);
		    map.put(weakReference, value);
		}
		System.out.println("map.size->" + map.size());
		
//		---------------------------------------
		Thread thread = new Thread(() -> {
		    try {
		        int cnt = 0;
		        WeakReference<byte[]> k;
		        while((k = (WeakReference) referenceQueue.remove()) != null) {
		            System.out.println((cnt++) + "回收了:" + k);
		        }
		    } catch(InterruptedException e) {
		        //结束循环
		    }
		});
		thread.setDaemon(true);
		thread.start();
	}

	public static void main(String[] args) {
		TestWeakReferenceQueue tq = new TestWeakReferenceQueue();
		tq.m1();

	}

}
